import Vue from "vue";
import Vuex from "vuex";

import { userLogin, userOut } from "../api/user.js";
import {
  setUserInfo,
  setUserToken,
  getUserInfo,
  getUserToken,
  removeUserInfo,
  removeUserToken,
} from "../utils/auth";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: getUserInfo() ? getUserInfo() : null,
    token: getUserToken() ? getUserToken() : "",
  },
  mutations: {
    // 登录 => 保存用户数据
    changeUser(state, payload) {
      state.user = payload;
      setUserInfo(payload);
      setUserToken(payload.token);
    },
    // 退出登录 => 删除登录数据
    clearState(state) {
      removeUserInfo();
      removeUserToken();
      state.user = null;
      state.token = "";
    },
  },
  actions: {
    // 登录
    login({ commit }, data) {
      return new Promise((res, rej) => {
        userLogin(data.username, data.password)
          .then((response) => {
            // 将数据返回给页面
            res(response);
            commit("changeUser", response.data.data);
          })
          .catch((error) => rej(error));
      });
    },
    // 退出登录
    loginOut({ commit }) {
      return new Promise((res, rej) => {
        userOut()
          .then((resolve) => {
            res(resolve);
            commit("clearState");
          })
          .catch((error) => rej(error));
      });
    },
  },
  modules: {},
});
